package com.dgut.common.filter;

import com.dgut.common.service.AdministratorService;
import com.dgut.common.service.EmployeeService;
import com.dgut.common.util.JwtUtil;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * 判断token
 * 有没有过期
 * 最后还要配置到security中
 */

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private AdministratorService administratorService;

    @Autowired
    private EmployeeService employeeService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws RuntimeException,ServletException, IOException {
        //获取token,从请求头中
        String token = request.getHeader("token");
        //字符串为空
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userName;
        Claims claims = null;
        try {
            //将token解密
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            log.info("token不合法");
            throw new RuntimeException("token不合法");
        }
        userName = claims.getSubject();
        //从数据库里面查询，看是管理员还是员工，赋予不同权限
        LoginUser loginUser = getLoginUser(userName);
        log.info("loginUser = {}", loginUser);
        if(Objects.isNull(loginUser.getUser())){
            throw new RuntimeException("用户未登录");
        }
        //获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser, null, ( loginUser).getAuthorities());
        //将信息存入 SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }

    private LoginUser getLoginUser(String userName) {
        LoginUser loginUser = new LoginUser();
        List<String> permission =  new ArrayList<>();
        User user = administratorService.getByUserName(userName);
        if (user == null) {
            permission.add("employee");
            user = employeeService.getByUserName(userName);
        } else {
            permission.add("admin");
        }
        loginUser.setUser(user);
        loginUser.setPermission(permission);
        return loginUser;
    }

}






